package cn.kgc.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.lang.util.ByteSource;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author 课工场
 * @date 2024/12/6
 * @description
 */
public class CustomerRealm extends AuthorizingRealm {

    // 授权   用户访问受限资源时  自动调用该方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("---------CustomerRealm doGetAuthorizationInfo-----------");
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal();
        // 认证通过的用户名
        System.out.println("primaryPrincipal = " + primaryPrincipal);
        // TODO  根据身份信息 查询数据库   返回用户的权限信息    角色  权限字符串

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 添加角色信息
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("super");

        //添加权限字符串
        simpleAuthorizationInfo.addStringPermission("sys:user:add");


        return simpleAuthorizationInfo ;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        if ("root".equals(username)){
            SimpleAccount simpleAccount =
                    new SimpleAccount("root", "2d215297cf2a75d4211cebca82c6ae9c", ByteSource.Util.bytes("dbr5r3h2"), this.getName());
            return simpleAccount;
        }
        return null;
    }
}
